#include "cardcontrollerform.h"
#include "ui_cardcontrollerform.h"
#include <iostream>

CardControllerForm::CardControllerForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CardControllerForm),
    on(true)
{
    ui->setupUi(this);

    // QTimer
    actualizeTimer = new QTimer();
    connect( actualizeTimer, SIGNAL(timeout()), this, SLOT(on_actualize()) );

    ui->motorSlider->setRange(-90,90);
    ui->motorSlider->setValue(0);
    char buffer [5];
    itoa(ui->motorSlider->value(),buffer,10);
    ui->slideLabel->setText(buffer);
    connect( ui->motorSlider, SIGNAL(sliderReleased()), this, SLOT(on_sliderSet()));
    connect( ui->motorSlider, SIGNAL(valueChanged(int)), this, SLOT(on_sliderChange(int)));
    connect(ui->motorSlider, SIGNAL(sliderMoved(int)), this, SLOT(on_sliderClick(int)));

    ui->lcdTemp1->setDigitCount(6);
    ui->lcdTemp2->setDigitCount(6);
    ui->lcdTemp1->setPalette(Qt::black);
    ui->lcdTemp2->setPalette(Qt::black);
}

CardControllerForm::~CardControllerForm()
{
    delete ui;
    delete actualizeTimer;
}

void CardControllerForm::display(QString message)
{
    QStringList list = message.split(";");
    QStringList list2 = list[0].split(":");
    std::cout << list2[0].toStdString() << " " << list2[1].toStdString() << std::endl;
    ui->lcdTemp1->display(list2[1].toDouble());

    QStringList list3 = list[1].split(":");
    ui->lcdTemp2->display(list3[1].toDouble());
}

void CardControllerForm::on_ledButton_clicked()
{
    if( on )
    {
        ui->ledButton->setText("Eteindre led");
        on = false;
        emit ledOn();
    }
    else
    {
        ui->ledButton->setText("Allumer led");
        on = true;
        emit ledOff();
    }
}

void CardControllerForm::on_actualizeButton_clicked()
{
    on_actualize();
}

void CardControllerForm::on_sendButton_clicked()
{
    QString message = ui->messageInputText->toPlainText();
    if( ! message.isEmpty() )
    {
        emit messageSent(message);
        ui->messageInputText->clear();
    }
}

void CardControllerForm::on_actualizeRadioButton_clicked()
{
    if( ui->actualizeRadioButton->isChecked() )
    {
        on_actualize();
        actualizeTimer->start(2000);
    }
    else
    {
        actualizeTimer->stop();
    }
}

void CardControllerForm::on_actualize()
{
    emit actualized();
}

void CardControllerForm::on_sliderChange(int val)
{
    char buffer [5];
    itoa(val,buffer,10);
    ui->slideLabel->setText(buffer);
}

void CardControllerForm::on_sliderSet()
{
    int val = ui->motorSlider->value();
    char buffer [5];
    itoa(val,buffer,10);
    ui->slideLabel->setText(buffer);
    emit motorSlide(val);
}

void CardControllerForm::on_sliderClick(int val)
{
    char buffer [5];
    itoa(val,buffer,10);
    ui->slideLabel->setText(buffer);
    std::cout<<"benoit a eu 15.83"<<std::endl;
}
